package com.jluzh10.learning.web.exception;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yzg
 * @create 2019/5/22
 *
 * 自定义拦截全局异常处理器（以保证可以拦截框架下的所有异常
 */

public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

//        MyException myException=null;
//        if (ex instanceof MyException) {
//            myException = (MyException) ex;
//        } else {//如果该异常类型不是系统自定义的异常，构造一个自定义的异常类型（信息为“未知错误”）
//            myException = new MyException("未知错误");
//        }
        //使用fastjson返回错误信息
        FastJsonJsonView jsonView = new FastJsonJsonView();
        Map<String,Object> map=new HashMap<>();
        map.put("code",500);
        map.put("message",ex.getMessage());
        jsonView.setAttributesMap(map);
        ModelAndView mv=new ModelAndView();
        mv.setView(jsonView);
        return mv;
    }
}
